import Vue from 'vue';
import VueRouter from 'vue-router';
import Login from '@/views/login/Login';
import Home from '@/views/home/Home';
import store from "@/store";
import {getToken, getUserInfo, removeRouters, removeToken, removeUserInfo} from "@/api/auth";
import {initMenu} from "@/utils/menus";
Vue.use(VueRouter);


const routes = [
    {
        path: '/',
        name: '登录',
        component: Login,
    },
    {
        path: '/home',
        name: '主页面',
        component: Home
    },
];

const router = new VueRouter({
    routes
});
router.beforeEach(async (to, from, next) => {
    console.log(to, from);
    // 是否登录
    let strUserInfo = getUserInfo();
    let token = getToken();
    if (strUserInfo && token) {
        if (store.getters.app.routes.length <= 0) {
            await initMenu(router, store);
            next({...to, replace: true});
        } else {
            //     // 判断用户信息是否存在
            //     if (!window.sessionStorage.getItem("user")) {
            //         return getRequest(store.state.loginServiceApi + '/login/info').then(res => {
            //             if (res.code == 200) {
            //                 // 存入用户信息
            //                 window.sessionStorage.setItem("user", JSON.stringify(res.data))
            store.commit('app/setUserInfo', JSON.parse(strUserInfo));
            //                 next()
            //                 return;
            //             }
            //         })
            //     }
            //     if (!store.state.user) {
            //         store.commit('initUser', JSON.parse(window.sessionStorage.getItem("user")))
            //     }
            next();
        }
    } else {
        removeToken();
        removeUserInfo();
        removeRouters();
        if (to.path == '/') {
            next();
        } else {
            next('/?redirect=' + to.path);
        }
    }
});
export default router
